﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Management;
using System.Configuration;

namespace HealthMonitoring
{
    internal class MemoryDumpEventProvider : System.Web.Management.WebEventProvider
    {
   
        
        public MemoryDumpEventProvider()
            : base()
        {
        }


        // Flush the input buffer if required.
        public override void Flush()
        {

        }


        // Shutdown the provider.
        public override void Shutdown()
        {
            Flush();
        }

    

        /// <summary>
        /// Process the event that has been raised.
        /// </summary>
        /// <param name="raisedEvent"></param>
        public override void ProcessEvent(WebBaseEvent raisedEvent)
        {
            WebBaseErrorEvent errorEvent = raisedEvent as WebBaseErrorEvent;

            if (errorEvent == null)
            {
                MemoryDumpManager.RaiseDumpCreationFailedException(MemoryDumpManager.Constants.WarningForUnsupportedEventtype, errorEvent.ErrorException);

            }

            if (IsMiniMemoryDumpTaken(errorEvent.ErrorException))
            {
                return;
            }

        
            try
                {
                    MemoryDumpManager dumpManager = new MemoryDumpManager(errorEvent.ErrorException);

                    dumpManager.CreateMiniDump();
                }
            catch (Exception Ex)
                {
                    MemoryDumpManager.RaiseDumpCreationFailedException(MemoryDumpManager.Constants.ErrorMessageForDumpNotCreated, Ex, errorEvent.ErrorException);
                }

            
        }

        private static bool IsMiniMemoryDumpTaken(Exception ex)
        {
            if (ex.GetBaseException().Data.Contains(MemoryDumpManager.Constants.MiniDumpTaken))
            {
                return true;
            }
            ex.GetBaseException().Data.Add(MemoryDumpManager.Constants.MiniDumpTaken, true);
            return false;
        }

      
         
            
            
        
    }
}

